package org.xwalk.core;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * This class represents a navigation item and is managed in XWalkNavigationHistory.
 */

public class XWalkNavigationItem   {

    private ArrayList<Object> constructorTypes;
    private ArrayList<Object> constructorParams;
    private ReflectMethod postWrapperMethod;


    private XWalkCoreWrapper coreWrapper;
    private Object bridge;

    protected Object getBridge() {
        return bridge;
    }

    public XWalkNavigationItem(Object bridge) {
        this.bridge = bridge;
        reflectionInit();
    }

    /**
     * Get the url of current navigation item.
     * @return the string of the url.
     * @since 1.0
     */
    public String getUrl() {
        try {
            return (String)getUrlMethod.invoke();
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                throw new RuntimeException("Crosswalk's APIs are not ready yet");
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        return null;
    }

    private ReflectMethod getUrlMethod = new ReflectMethod(null, "getUrl");

    /**
     * Get the original url of current navigation item.
     * @return the string of the original url.
     * @since 1.0
     */
    public String getOriginalUrl() {
        try {
            return (String)getOriginalUrlMethod.invoke();
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                throw new RuntimeException("Crosswalk's APIs are not ready yet");
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        return null;
    }

    private ReflectMethod getOriginalUrlMethod = new ReflectMethod(null, "getOriginalUrl");

    /**
     * Get the title of current navigation item.
     * @return the string of the title.
     * @since 1.0
     */
    public String getTitle() {
        try {
            return (String)getTitleMethod.invoke();
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                throw new RuntimeException("Crosswalk's APIs are not ready yet");
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        return null;
    }

    private ReflectMethod getTitleMethod = new ReflectMethod(null, "getTitle");


    void reflectionInit() {
        XWalkCoreWrapper.initEmbeddedMode();

        coreWrapper = XWalkCoreWrapper.getInstance();
        if (coreWrapper == null) {
            XWalkCoreWrapper.reserveReflectObject(this);
            return;
        }

        getUrlMethod.init(bridge, null,
                "getUrlSuper");
        getOriginalUrlMethod.init(bridge, null,
                "getOriginalUrlSuper");
        getTitleMethod.init(bridge, null,
                "getTitleSuper");
    }

}
